/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */
package com.mmm.station.security.servletFilter;


import com.mmm.station.security.constant.Constant;
import com.mmm.station.security.method.ExclusionUrls;
import com.mmm.station.security.method.Subject;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

@WebFilter(filterName = "mSecurity",urlPatterns = "/*")
public class MAbstractFilter extends MServletContext implements Filter {

    private Logger log = LogManager.getLogger(this.getClass());
    protected FilterConfig filterConfig;
    public FilterConfig getFilterConfig() {
        return filterConfig;
    }

    public void setFilterConfig(FilterConfig filterConfig) {
        this.filterConfig = filterConfig;
        setServletContext(filterConfig.getServletContext());
    }

    public final void init(FilterConfig filterConfig) throws ServletException {
        setFilterConfig(filterConfig);
        try {
            onFilterConfigSet();
        } catch (Exception e) {
            if (e instanceof ServletException) {
                throw (ServletException) e;
            } else {
                if (log.isErrorEnabled()) {
                    log.error("Unable to start Filter: [" + e.getMessage() + "].", e);
                }
                throw new ServletException(e);
            }
        }
    }


    protected void onFilterConfigSet() throws Exception {
    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        if (ExclusionUrls.ex){
            String uri = request.getServletPath();
            if(getEx(uri)) {
                //所有人都能请求到的URI，放行
                chain.doFilter(request, response);
            } else {    //下面是判断是否有session，也就是用户是否已登录状态；
                HttpSession session = request.getSession();
                Object user = session.getAttribute(Constant.AUTHINFO);
                if(user == null) {
                    log.info("URI:" + uri + ">>>>filter！");
                    String responseType = Subject.getInstance().getManager().getResponseType();
                    if( responseType != null){
                        if (responseType .equals("json")){
                            response.setContentType("application/json; charset=utf-8");
                            PrintWriter printWriter = response.getWriter();
                            printWriter.println(Subject.getInstance().getManager().getAuthJsonContent());
                            printWriter.close();
                        }else {
                            request.getRequestDispatcher(Subject.getInstance().getManager().getAuthSispatcherPath()).forward(request,response);
                        }
                    }else {
//                        String url = request.getContextPath()+"/mError.html";
                        request.getRequestDispatcher("mError.html").forward(request,response);
                    }

                } else {
                    chain.doFilter(request, response);
                }
            }

        }else {
            chain.doFilter(request, response);
        }

    }


    public void destroy() {
    }



    public boolean getEx(String requestUrl){
        List<String> fulUrls = ExclusionUrls.fulUrls;
        List<String> beginUrls = ExclusionUrls.beginUrls;
        List<String> endUrls = ExclusionUrls.endUrls;
        if (fulUrls != null){
            for (String url : fulUrls){
                if (url.equals(requestUrl)){
                    return true;
                }
            }
        }
        if (beginUrls != null){
            for (String url : beginUrls){
                if (requestUrl.startsWith(url)){
                    return true;
                }
            }
        }
        if (endUrls != null){
            for (String url : endUrls){
                if (requestUrl.endsWith(url)){
                    return true;
                }
            }
        }
        return  false;


    }

}